package android.team.app.network;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import android.content.Context;
import android.team.app.info.WebserviceConfig;

public class AsyncHttpGet extends AsyncHttpBase {

	public AsyncHttpGet(Context context, AsyncHttpResponseListener listener,
			List<NameValuePair> params) {
		super(context, listener, params);
	}

	public AsyncHttpGet(Context context,
			AsyncHttpResponseProcess httpResponseProcess,
			List<NameValuePair> params) {
		super(context, httpResponseProcess, params);
	}

	@SuppressWarnings("deprecation")
	@Override
	protected String request(String url) {
		try {
			HttpParams params = new BasicHttpParams();
			if (parameters != null) {
				Iterator<NameValuePair> iterator = parameters.iterator();
				int i = 0;
				while (iterator.hasNext()) {
					NameValuePair nv = iterator.next();
					params.setParameter(nv.getName(), nv.getValue());
					if (i == 0) {
						url += "?"	+ URLEncoder.encode(nv.getName() + "="	+ URLEncoder.encode(nv.getValue()));
					} else {
						url += "&"	+ URLEncoder.encode(nv.getName() + "="	+ URLEncoder.encode(nv.getValue()));
					}

					i++;
				}
			}
			HttpConnectionParams.setConnectionTimeout(params,	WebserviceConfig.NETWORK_TIMEOUT);
			HttpConnectionParams.setSoTimeout(params,WebserviceConfig.NETWORK_TIMEOUT);

			HttpClient httpClient = CreateHttpClient(params);
			HttpGet httpGet = new HttpGet(url);
			
			try {
				response = httpClient.execute(httpGet);
				statusCode =STATUS_NETWORK_OK;
				
			} catch(java.net.SocketTimeoutException e){
				statusCode = STATUS_NETWORK_TIMEOUT;
			}
			catch(javax.net.ssl.SSLException e){
				statusCode = STATUS_NETWORK_EXCEIPTION;
			}
			catch(org.apache.http.conn.ConnectTimeoutException e){
				statusCode = STATUS_NETWORK_TIMEOUT;
			}
			catch(ClientProtocolException e){
				statusCode = STATUS_NETWORK_ERROR;
			}
			catch(IOException e){
				statusCode = STATUS_NETWORK_ERROR;
			}
			catch (Exception e) {
				statusCode = STATUS_NETWORK_EXCEIPTION;
			}
			
		} catch (Exception e) {
			statusCode = STATUS_NETWORK_EXCEIPTION;
		}
		return null;
	}
}
